DECLARE @TMP TABLE(
	IDPOLIZZA INT,
	CODPREN CHAR(14)
)
/*INSERT INTO @TMP (CODPREN)
	SELECT distinct S.codpren FROM LINEE L (NOLOCK)
	INNER JOIN CONFIGLINEE CL (NOLOCK) ON  CL.CODLIN=L.CODLIN 
	INNER JOIN CORSE C (NOLOCK) ON C.COD_CFG_LINEA=CL.COD_CFG_LINEA
	INNER JOIN SEQBIG S (NOLOCK) ON S.CODCORSA=C.CODCORSA
	INNER JOIN BIGLIE B (NOLOCK) ON B.CODPREN=S.CODPREN AND B.N_MOD=S.N_MOD 
	WHERE L.MACROREGIONE='AL' AND B.ANNULLATO=1 AND S.CODPREN NOT IN ('IP991406250038')
	AND S.CODPREN IN (SELECT CODPREN FROM P_POLIZZE)
*/

INSERT INTO @TMP (IDPOLIZZA, CODPREN)
	SELECT IDPOLIZZA, CODPREN FROM P_POLIZZE

DECLARE @CODPOLIZZA INT, @CODPREN CHAR(14)
DECLARE CURSORE CURSOR FOR SELECT IDPOLIZZA, CODPREN FROM @TMP 
OPEN CURSORE
FETCH NEXT FROM CURSORE INTO @CODPOLIZZA, @CODPREN
WHILE @@FETCH_STATUS>=0
BEGIN

	delete from p_polizze_pax where IDPOLIZZA = @codpolizza
	delete from p_polizze_sis where IDPOLIZZA = @codpolizza
	delete from p_polizze_veicoli where IDPOLIZZA = @codpolizza
	delete from p_polizze_accessori where IDPOLIZZA = @codpolizza
	delete from p_polizze where IDPOLIZZA = @codpolizza
	delete from p_polizze_diritti where idpolizza=@idpolizza
	delete from p_polizze_dirittifissi where idpolizza=@idpolizza
	delete from p_polizze_dettaglio_merce where idpolizza=@idpolizza

	delete from p_polizze_pax_arch where IDPOLIZZA = @codpolizza
	delete from p_polizze_sis_arch where IDPOLIZZA = @codpolizza
	delete from p_polizze_veicoli_arch where IDPOLIZZA = @codpolizza
	delete from p_polizze_accessori_arch where IDPOLIZZA = @codpolizza
	delete from p_polizze_arch where IDPOLIZZA = @codpolizza
	delete from p_polizze_diritti_arch where idpolizza=@idpolizza
	delete from p_polizze_dirittifissi_arch where idpolizza=@idpolizza
	delete from p_polizze_dettaglio_merce_arch where idpolizza=@idpolizza
	

	delete from dettax where codpren = @codpren
	DELETE FROM DETTAX_IVA WHERE CODPREN = @CODPREN
	delete from biglietti where codpren = @codpren
	delete from movimenti where codpren = @codpren
	delete from commissioni_dett where CODPREN=@codpren
	delete from passeg where codpren = @codpren
	delete from detbig where codpren = @codpren
	delete from entbig where codpren = @codpren
	delete from seqbig where codpren = @codpren
	delete from biglie where codpren = @codpren
	DELETE FROM JBOARD_PAX WHERE CODPREN=@CODPREN
	DELETE FROM JBOARD_VEI WHERE CODPREN=@CODPREN

	delete from dettax_arch where codpren = @codpren
	DELETE FROM DETTAX_IVA_ARCH WHERE CODPREN = @CODPREN
	delete from passeg_arch where codpren = @codpren
	delete from detbig_arch where codpren = @codpren
	delete from entbig_arch where codpren = @codpren
	delete from seqbig_arch where codpren = @codpren
	delete from biglie_arch where codpren = @codpren

	DELETE FROM JBOARD_PAX_ARCH WHERE CODPREN=@CODPREN
	DELETE FROM JBOARD_VEI_ARCH WHERE CODPREN=@CODPREN
	
FETCH NEXT FROM CURSORE INTO @CODPOLIZZA, @CODPREN
END
CLOSE CURSORE
DEALLOCATE CURSORE